package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.BehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApFollow;
import com.heima.user.mapper.ApFollowMapper;
import com.heima.user.service.ApFollowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import springfox.documentation.spring.web.json.Json;

import java.util.Date;
import java.util.jar.JarEntry;

@Service
public class ApFollowServiceImpl extends ServiceImpl<ApFollowMapper, ApFollow> implements ApFollowService {
    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult followAndNO(UserRelationDto userRelationDto) {
        ApFollow apFollow = new ApFollow();
        apFollow.setArticleId(userRelationDto.getArticleId());
        apFollow.setAuthorId(userRelationDto.getAuthorId());
        apFollow.setCreateTime(new Date());
        apFollow.setUserId(userRelationDto.getUserId());
        apFollow.setOperation(userRelationDto.getOperation());
        String key = (userRelationDto.getUserId()).toString() + "__" + (userRelationDto.getArticleId()).toString();
        if (userRelationDto.getOperation() == 0) {
            LambdaQueryWrapper<ApFollow> Wrapper = new LambdaQueryWrapper<>();
            Wrapper.eq(ApFollow::getArticleId, userRelationDto.getArticleId()).eq(ApFollow::getAuthorId, userRelationDto.getAuthorId()).eq(ApFollow::getUserId, userRelationDto.getUserId());
            cacheService.delete(key);
            this.remove(Wrapper);
            return ResponseResult.okResult(200, "取消关注成功");
        } else {

            cacheService.set(key, JSON.toJSONString(apFollow));
            this.save(apFollow);
        }
        return ResponseResult.okResult(200, "关注成功");

    }
}
